import { TenantModel } from '../../schemas/system/Tenant';
import { Tenant } from '../../types';
import { HttpError } from '../../exceptions/HttpError';

export class TenantRepository {
  // 获取所有租户
  async findAll(): Promise<Tenant[]> {
    try {
      return await TenantModel.find().sort({ sort: -1 }).populate('createdBy updatedBy').lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`获取租户列表失败: ${error.message}`);
    }
  }



  // 根据ID获取租户
  async findById(id: string): Promise<Tenant | null> {
    try {
      const tenant = await TenantModel.findById(id).populate('createdBy updatedBy').lean();
      if (!tenant) {
        throw HttpError.notFound('租户不存在');
      }
      return tenant;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取租户信息失败: ${error.message}`);
    }
  }


    // 创建租户
    async create(tenantData: Partial<Tenant>): Promise<Tenant> {
      try {
        const tenant = new TenantModel(tenantData);
        return await tenant.save();
      } catch (error: any) {
        if (error.code === 11000) {
          throw HttpError.unprocessableEntity('租户ID已被注册', error.errors);
        }
        if (error.name === 'ValidationError') {
          throw HttpError.unprocessableEntity('数据验证失败1', error.errors);
        }
        throw HttpError.internalServerError(`创建租户失败2: ${error.message}`);
      }
    }

    // 更新租户
    async update(id: string, tenantData: Partial<Tenant>): Promise<Tenant | null> {
      try {
        // 移除密码字段，防止通过更新接口修改密码
        const { ...updateData } = tenantData;

        const tenant = await TenantModel.findByIdAndUpdate(
          id,
          updateData,
          { new: true, runValidators: true }
        );

        if (!tenant) {
          throw HttpError.notFound('租户不存在');
        }

        return tenant;
      } catch (error: any) {
        if (error instanceof HttpError) throw error;
        if (error.code === 11000) {
          throw HttpError.conflict('租户ID已被注册');
        }
        if (error.name === 'ValidationError') {
          throw HttpError.unprocessableEntity('数据验证失败', error.errors);
        }
        throw HttpError.internalServerError(`更新用户失败: ${error.message}`);
      }
    }

    // 删除用户
    async delete(id: string): Promise<boolean> {
      try {
        const result = await TenantModel.findByIdAndDelete(id);
        if (!result) {
          throw HttpError.notFound('租户不存在');
        }
        return true;
      } catch (error: any) {
        if (error instanceof HttpError) throw error;
        throw HttpError.internalServerError(`删除租户失败: ${error.message}`);
      }
    }

    // 获取用户数量
    async count(): Promise<number> {
      try {
        return await TenantModel.countDocuments();
      } catch (error: any) {
        throw HttpError.internalServerError(`统计租户数量失败: ${error.message}`);
      }
    }

    // 分页查询租户
    async findWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Tenant[], page: number, limit: number, total: number, pages: number }> {
      try {
        const skip = (page - 1) * limit;
        const [list, total] = await Promise.all([
          TenantModel.find().sort({ createdAt: -1 }).skip(skip).limit(limit).populate('createdBy updatedBy').lean(),
          TenantModel.countDocuments()
        ]);

        return {
          list,
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        };
      } catch (error: any) {
        throw HttpError.internalServerError(`分页查询租户失败: ${error.message}`);
      }
    }
}

export default new TenantRepository();
